﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Collection.Interfaces;
using Collection.Entities;
using Top.Api.Request;
using Top.Api.Response;
using Top.Api.Domain;
using System.Threading;
using Collection.Utilities;
namespace Collection.Core
{
    /// <summary>
    /// 商品信息采集器
    /// </summary>
    public class MerchandiseCollector : CollectorBase
    {
        /// <summary>
        /// 商品采集器实例
        /// </summary>
        public readonly static MerchandiseCollector Instance;

        /// <summary>
        /// 私有构造函数
        /// </summary>
        private MerchandiseCollector()
        {
            this.temporaryStack = new StringBuilder();
            this.temporaryDictionary = new Dictionary<Int64, TaobaokeItem>();
        }

        /// <summary>
        /// 静态构造
        /// </summary>
        static MerchandiseCollector()
        {
            Instance = new MerchandiseCollector();
        }

        /// <summary>
        /// 最大页码数
        /// </summary>
        private int MaxPageNo
        {
            get
            {
                return 10;
            }
        }

        /// <summary>
        /// 淘宝客商品数字id串容器
        /// </summary>
        private StringBuilder temporaryStack;

        /// <summary>
        ///  淘宝客商品数字id串容器
        /// </summary>
        public StringBuilder TemporaryStack
        {
            get { return temporaryStack; }
        }

        /// <summary>
        /// 临时字典
        /// </summary>
        private IDictionary<Int64, TaobaokeItem> temporaryDictionary;

        /// <summary>
        /// 临时字典
        /// </summary>
        public IDictionary<Int64, TaobaokeItem> TemporaryDictionary
        {
            get { return temporaryDictionary; }
        }

        /// <summary>
        /// 清空临时字典
        /// </summary>
        private void ClearTempDictionary()
        {
            this.temporaryDictionary.Clear();
        }

        /// <summary>
        /// 清空淘宝客商品数字id串容器
        /// </summary>
        private void ClearTempStack()
        {
            this.temporaryStack.Remove(0, this.TemporaryStack.Length);
        }

        /// <summary>
        /// 初始化临时容器
        /// </summary>
        public void InitializeTemporaryContainer()
        {
            this.ClearTempStack();
            this.ClearTempDictionary();
        }

        /// <summary>
        /// 设置单页记录的页大小
        /// </summary>
        private Int32 PageSize
        {
            get
            {
                return 40;
            }
        }

        /// <summary>
        /// 淘宝客商品数字id串.最大输入10个（针对详细信息的请求）
        /// </summary>
        private Int32 DetailRequestSize
        {
            get { return 10; }
        }

        /// <summary>
        /// 根据指定的分类获取淘宝客推荐商品
        /// </summary>
        /// <param name="catalogId">分类Id</param>
        public void GatherCommodities(Int64 catalogId)
        {
            TaobaokeItemsGetRequest itemsRequest = new TaobaokeItemsGetRequest();
            itemsRequest.Fields = "num_iid,title,nick,pic_url,price,click_url,commission,props,commission_rate,commission_num,commission_volume,shop_click_url,seller_credit_score,item_location,volume";
            itemsRequest.Nick = CollectorBase.Nick;
            itemsRequest.StartCredit = "1crown";
            itemsRequest.EndCredit = "5goldencrown";
            itemsRequest.Sort = "credit_desc";
            itemsRequest.StartTotalnum = "10";
            itemsRequest.EndTotalnum = "1000000";
            itemsRequest.Cid = catalogId;
            itemsRequest.PageNo = 1;
            itemsRequest.PageSize = this.PageSize;

            TaobaokeItemsDetailGetRequest detailRequest = new TaobaokeItemsDetailGetRequest();
            detailRequest.Fields = "num_iid,cid,props,product_id,item_img,item_img.url,list_time,delist_time,modified";
            detailRequest.Nick = CollectorBase.Nick;
            foreach (var city in Utility.Cities)
            {
                itemsRequest.Area = city;
                this.GatherCommodities(itemsRequest, detailRequest, catalogId);
            }
        }

        public void GatherCommodities(TaobaokeItemsGetRequest itemsRequest, TaobaokeItemsDetailGetRequest detailRequest, Int64 catalogId)
        {
            //线程阻塞10秒
            Thread.Sleep(1000);
            TaobaokeItemsGetResponse response = CollectorBase.TaobaoApi.Execute(itemsRequest);

            this.SinglePageHandle(response.TaobaokeItems, detailRequest);

            //计算出分页总数
            var pageCount = response.TotalResults / this.PageSize;

            //计算出余下记录数
            var surplus = response.TotalResults % this.PageSize;

            if (surplus > 0)
            {
                pageCount += 1;
            }
            if (pageCount > this.MaxPageNo)
            {
                pageCount = this.MaxPageNo;
            }
            for (Int32 i = 2; i <= pageCount; i++)
            {
                itemsRequest.PageNo = i;
                response = CollectorBase.TaobaoApi.Execute(itemsRequest);
                this.SinglePageHandle(response.TaobaokeItems, detailRequest);
            }
        }

        /// <summary>
        /// 获取商品详情信息
        /// </summary>
        public TaobaokeItemsDetailGetResponse GatherMerchandiseDetails(TaobaokeItemsDetailGetRequest detailRequest, String itemIds)
        {
            detailRequest.NumIids = itemIds;

            //线程阻塞10秒
            Thread.Sleep(1000);
            return CollectorBase.TaobaoApi.Execute(detailRequest);
        }

        /// <summary>
        /// 针对单页上的记录进行获取详细信息的处理
        /// </summary>
        /// <param name="items">单页记录量（这里最大为PageSize设置的值）</param>
        /// <param name="detailRequest">详细信息获取的接口对象</param>
        private void SinglePageHandle(IList<TaobaokeItem> items, TaobaokeItemsDetailGetRequest detailRequest)
        {
            this.InitializeTemporaryContainer();

            //剩余数
            var surplus = items.Count % this.DetailRequestSize;
            Int32 i = 0;
            for (; i < items.Count - surplus; i++)
            {
                this.TemporaryStack.Append(String.Format("{0},", items[i].NumIid));
                this.TemporaryDictionary.Add(items[i].NumIid, items[i]);
                if ((i + 1) % this.DetailRequestSize == 0)
                {
                    this.TemporaryStack.Remove(this.TemporaryStack.Length - 1, 1);
                    this.SaveMerchandise(this.TemporaryDictionary, this.GatherMerchandiseDetails(detailRequest, this.TemporaryStack.ToString()).TaobaokeItemDetails);
                    this.InitializeTemporaryContainer();
                }
            }

            if (surplus > 0)
            {
                for (; i < items.Count; i++)
                {
                    this.TemporaryStack.Append(String.Format("{0},", items[i].NumIid));
                    this.TemporaryDictionary.Add(items[i].NumIid, items[i]);
                }
                this.TemporaryStack.Remove(this.TemporaryStack.Length - 1, 1);
                this.SaveMerchandise(this.TemporaryDictionary, this.GatherMerchandiseDetails(detailRequest, this.TemporaryStack.ToString()).TaobaokeItemDetails);
                this.InitializeTemporaryContainer();
            }
        }

        /// <summary>
        /// 将采集的商品信息保存到本地
        /// </summary>
        /// <param name="items">商品列表</param>
        /// <param name="itemDetails">商品明细</param>
        private void SaveMerchandise(IDictionary<Int64, TaobaokeItem> items, IList<TaobaokeItemDetail> itemDetails)
        {
            for (var i = 0; i < itemDetails.Count; i++)
            {
                var merchandise = items[itemDetails[i].Item.NumIid].ToMerchandise(itemDetails[i]);
                if (CollectionServiceFactory.MerchandiseService.HasMerchandise(itemDetails[i].Item.Cid, itemDetails[i].Item.NumIid))
                {
                    CollectionServiceFactory.MerchandiseService.Update(merchandise);
                }
                else
                {
                    CollectionServiceFactory.MerchandiseService.Insert(merchandise);
                }
                //下载图片
                ImageLoader.Loader.Download(merchandise);
            }
        }
    }
}
